﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace LeastSquareMethod.Models
{
    internal class RegressionModel
    {
        /// <summary>
        /// 工具类，建立线性回归模型
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        public static void Regression (List<string> x, List<string> y)
        {
            //求和
            double sumx = 0, sumy = 0;
            for (int i = 0; i< 10;i ++)
            {
                sumx += Convert.ToDouble(x[i]);
                sumy += Convert.ToDouble(y[i]);
            }
            //求平均值
            double Avgx = sumx / 10;
            double Avgy = sumy / 10;
            //利用公式求a、b
            double numerator = 0, denominator = 0;
            for (int k = 0; k < 10; k++)
            {
                numerator += (Convert.ToDouble(x[k]) - Avgx) *
                             (Convert.ToDouble(y[k]) - Avgy);
                denominator += (Convert.ToDouble(x[k]) - Avgx) *
                               (Convert.ToDouble(y[k]) - Avgy);
            }
            double b = numerator / denominator;
            double a = Avgy - b * Avgx;
            //代入求2021年gdp
            double gdp2021 = a + b * 2021;
            Console.WriteLine(gdp2021); 
            Console.WriteLine($"误差为{(17.73-gdp2021)/17.73*100}%");
        }
            
    }
}
